package com.mall.sso.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.mall.manager.dao.TbUserMapper;
import com.mall.manager.pojo.TbUser;
import com.mall.manager.pojo.TbUserExample;
import com.mall.pojo.TaotaoResult;
import com.mall.sso.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service(timeout = 10000000)
@Component
@Transactional
public class LoginServiceImp implements LoginService {

    @Autowired
    TbUserMapper userMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Value("${session-expire}")
    private long session_Expire;

    @Value("${session_Key}")
    private String sessionKey_prefix;


    @Override
    public TaotaoResult login(String username, String password) {
        TbUserExample userExample = new TbUserExample();

        TbUserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);

        TaotaoResult taotaoResult = new TaotaoResult();
        List<TbUser> users = userMapper.selectByExample(userExample);

        if (users == null || users.size() == 0){
            return TaotaoResult.build(400, "用户名或密码错误");
        }

        TbUser user = users.get(0);

        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())){
            return TaotaoResult.build(400, "用户名或密码错误");
        }else {
            //验证通过生成token <-> sessionId
            String token = UUID.randomUUID().toString();
            //将用户信息写入redis中并设置过期时间实现全局共享，而不是像之前一样将其写入session域中
            //将密码设置为null再写进redis中，为了安全考虑
            user.setPassword(null);
            //每次登录都要重置一下token的过期时间
            stringRedisTemplate.opsForValue().set(sessionKey_prefix+token, JSONObject.toJSONString(user),
                    session_Expire, TimeUnit.MINUTES);

            return TaotaoResult.ok(token);
        }
    }

    @Override
    public void logout(String token) {
        String realSessionKey = sessionKey_prefix +token;
        String userJsonString = stringRedisTemplate.opsForValue().get(realSessionKey);
        if (! StringUtils.isEmpty(userJsonString)) {
            //删除token缓存，
            stringRedisTemplate.delete(realSessionKey);
        }
    }
}
